/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nxlv2.nomad.accessdb.dao.jdbc;

import com.nxlv2.nomad.accessdb.dao.DAOException;
import com.nxlv2.nomad.accessdb.dao.ISatisfactionDao;
import com.nxlv2.nomad.accessdb.dao.IncoherentResultException;
import com.nxlv2.nomad.accessdb.dao.NoResultException;
import com.nxlv2.nomad.businessobjects.Satisfaction;
import com.nxlv2.nomad.businessobjects.TauxSatisfaction;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Nastasia
 */
public class JdbcSatisfactionDao implements ISatisfactionDao{

    private static final Logger logger = LoggerFactory.getLogger(JdbcSatisfactionDao.class);
    private static final ConnectionManager manager = new ConnectionManager();

    /**
     * 
     * @param satisfaction
     * @throws DAOException 
     */
    @Override
    public void saveSatisfaction(Satisfaction satisfaction) throws DAOException {
        
        if (null == satisfaction) {
            throw new IllegalArgumentException("Can not save a null object.");
        }

        StringBuilder builder = new StringBuilder();

        builder.append("INSERT INTO satisfaction (idBase, tauxSatisfaction, message, date, dateCreation) ");
        builder.append("VALUES (?, AES_ENCRYPT(?,?), AES_ENCRYPT(?,?), ?, NOW())");

        String request = builder.toString();
        logger.debug("Insert satisfaction: {}", request);
        logger.debug("idBase: {}", satisfaction.getIdBase());
        logger.debug("Satisfaction: {}", satisfaction.getTauxSatisfaction().getValeur());
        logger.debug("Message satisfaction: {}", satisfaction.getMessage());
        logger.debug("Date satisfaction: {}", new java.sql.Date(satisfaction.getDate().getTime()));

        Connection con = manager.creerConnection();
        PreparedStatement ps;
        try {
            ps = con.prepareStatement(request, PreparedStatement.RETURN_GENERATED_KEYS);
        } catch (SQLException e) {
            logger.error("Can not prepare statement",e);
            throw new DAOException("Can not prepare statement.", e);
        }

        try {
            ps.setInt(1, satisfaction.getIdBase());
            ps.setString(2, satisfaction.getTauxSatisfaction().getValeur());
            ps.setString(3, manager.getKeyAES());
            ps.setString(4, satisfaction.getMessage());
            ps.setString(5, manager.getKeyAES());
            ps.setDate(6, new java.sql.Date(satisfaction.getDate().getTime()));
            ps.executeUpdate();

        } catch (SQLException e) {
            logger.error("Can not populate request with data.",e);
            throw new DAOException("Can not populate request with data.", e);
        }

        try {
            ResultSet rs = ps.getGeneratedKeys();

            int pk = 0;

            while (rs.next()) {
                pk = rs.getInt(1);
            }
            satisfaction.setIdAppli(pk);

        } catch (SQLException e) {
            logger.error("Can not execute insert in db.",e);
            throw new DAOException("Can not execute insert in db.", e);
        }
        manager.fermerConnection();
    }
    
    /**
     * 
     * @param id
     * @throws DAOException 
     */
    @Override
    public void deleteSatisfaction(int id) throws DAOException {
        
        if (id < 1) {
            throw new IllegalArgumentException("Can not save a null object.");
        }

        StringBuilder builder = new StringBuilder();
        builder.append("DELETE FROM satisfaction WHERE idAppli = ?");

        String request = builder.toString();
        logger.debug("Delete satisfaction: {}", request);

        Connection con = manager.creerConnection();
        PreparedStatement ps;
        try {
            ps = con.prepareStatement(request);
        } catch (SQLException e) {
            logger.error("Can not prepare statement", e);
            throw new DAOException("Can not prepare statement.", e);
        }

        try {
            ps.setInt(1, id);
            ps.executeUpdate();
        } catch (SQLException e) {
            logger.error("Can not delete satisfaction with id.", e);
            throw new DAOException("Can not delete satisfaction with id.", e);
        }
        manager.fermerConnection();
    }

    /**
     * 
     * @param satisfaction
     * @throws DAOException 
     */
    @Override
    public void updateSatisfaction(Satisfaction satisfaction) throws DAOException {

        
        if (null == satisfaction) {
            throw new IllegalArgumentException("Can not save a null object.");
        }

        StringBuilder builder = new StringBuilder();
        builder.append("UPDATE satisfaction ");
        builder.append("SET idBase = ?, tauxSatisfaction = AES_ENCRYPT(?,?),"
                + " message = AES_ENCRYPT(?,?), date = ?, dateModification = NOW() ");
        builder.append("WHERE idAppli = ?");

        String request = builder.toString();
        logger.debug("Update satisfaction: {}", request);

        Connection con = manager.creerConnection();
        PreparedStatement ps;
        try {
            ps = con.prepareStatement(request);
        } catch (SQLException e) {
            logger.error("Can not prepare statement");
            throw new DAOException("Can not prepare statement.", e);
        }

        try {
            ps.setInt(1, satisfaction.getIdBase());
            ps.setString(2, satisfaction.getTauxSatisfaction().getValeur());
            ps.setString(3, manager.getKeyAES());
            ps.setString(4, satisfaction.getMessage());
            ps.setString(5, manager.getKeyAES());
            ps.setDate(6, new java.sql.Date(satisfaction.getDate().getTime()));            
            ps.setInt(7, satisfaction.getIdAppli());
            ps.executeUpdate();
        } catch (SQLException e) {
            logger.error("Can not populate request with data.");
            throw new DAOException("Can not populate request with data.", e);
        }
        manager.fermerConnection();
    }
    
    /**
     * 
     * @param id
     * @return
     * @throws DAOException 
     */
    @Override
    public Satisfaction findById(int id) throws DAOException{
        
        StringBuilder builder = new StringBuilder();
        builder.append("SELECT idAppli, idBase, ");
        builder.append("AES_DECRYPT(tauxSatisfaction,?) AS tauxSatisfaction, ");
        builder.append("AES_DECRYPT(message,?) AS message, date ");
        builder.append("FROM satisfaction ");
        builder.append("WHERE idAppli = ?");

        String request = builder.toString();
        logger.debug("select satisfaction: {}", request);

        Connection con = manager.creerConnection();
        PreparedStatement ps;
        try {
            ps = con.prepareStatement(request);
        } catch (SQLException e) {
            logger.error("Can not prepare statement");
            throw new DAOException("Can not prepare statement.", e);
        }
        try {
            ps.setString(1, manager.getKeyAES());
            ps.setString(2, manager.getKeyAES());
            ps.setInt(3, id);
            ps.executeQuery();

        } catch (SQLException e) {
            logger.error("Can not select data with id.");
            throw new DAOException("Can not select data with id.", e);
        }
        ResultSet rst;
        try {
            rst = ps.getResultSet();
        } catch (SQLException e) {
            logger.error("Can not get resultset.");
            throw new DAOException("Can not get resultset.", e);
        }

        List<Satisfaction> satisfactions = null;
        try {
            satisfactions = map(rst);
        } catch (SQLException e) {
            logger.error("Can not populate map with result.", e);
            throw new DAOException("Can not populate map with result.", e);
        }

        if (null == satisfactions || satisfactions.isEmpty()) {
            throw new NoResultException("No satisfaction found with id " + id);
        }
        if (satisfactions.size() > 1) {
            throw new IncoherentResultException("Many records with a same id.");
        }
        manager.fermerConnection();
        return satisfactions.get(0);
    }    
    
    /**
     * 
     * @param rst
     * @return List<Satisfaction>
     * @throws SQLException 
     */
    private List<Satisfaction> map(ResultSet rst) throws SQLException {
        List<Satisfaction> satisfactions = new ArrayList<>();

        while (rst.next()) {

            Satisfaction satisfaction = new Satisfaction();
            satisfaction.setIdAppli(rst.getInt("idAppli"));
            satisfaction.setIdBase(rst.getInt("idBase"));
            satisfaction.setTauxSatisfaction(TauxSatisfaction.getByValeur(rst.getString("tauxSatisfaction")));
            satisfaction.setMessage(rst.getString("message"));
            satisfaction.setDate(rst.getDate("date"));
            satisfactions.add(satisfaction);
        }
        return satisfactions;
    }
}
